package com.example.lasttrain;

import java.util.ArrayList;

import com.example.lasttrain.common.DatabaseUtils;
import com.example.lasttrain.common.Defines;
import com.example.lasttrain.common.LeftTimeCalculate;
import com.example.lasttrain.common.TimeData;
import com.example.lasttrain.common.TrainEntry;
import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.Context;
import android.content.Intent;
import android.view.View.OnClickListener;

public class ListActivity extends Activity{

	ListView trainListView;
	Button createButton;
	Button alarmButton;
	ArrayList<TrainEntry> trainListItems;
	//Button btn_on;
	//Button btn_off; //Only the last alarm button is working fix
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_list);
		
		trainListView = (ListView)findViewById(R.id.train_list);
//		createButton = (Button)findViewById(R.id.create_button);
        // createButton.setOnClickListener(new ButtonClickList());
	}
	

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		ArrayList<TrainEntry> trainList = DatabaseUtils.getTitleList(this);

		TrainListAdapter listAdapter = new TrainListAdapter(this,
				R.layout.train_entry_context, trainList);
		
		trainListView.setAdapter(listAdapter);
	}

	private void moveToCreateActivity(){
		Intent intent = new Intent(this, CreateEditActivity.class);
		startActivity(intent);
	}
	
	private void moveToAlarmActivity(){
		Intent intent = new Intent(this, AlarmActivity.class);
		startActivity(intent);
	}
	
	private void moveToDetailActivity(int id){
		Intent intent = new Intent(this, DetailActivity.class);
		intent.putExtra(Defines.INTENT_DB_NUMBER, id);
		startActivity(intent);
	}
	
	private void moveToCreateActivityToEdit(int id){
		Intent intent = new Intent(this, CreateEditActivity.class);
		intent.putExtra(Defines.INTENT_DB_NUMBER, id);
		startActivity(intent);
	}
	
	private void moveToAlarmManageActivity(){
		Intent intent = new Intent(this, AlarmManageStart.class);
		startActivity(intent);
	}
	
	public void mOnClick(View v){
		switch(v.getId()){
//		case R.id.create_button:
//			moveToCreateActivity();
//			break;
		default:
			break;
		}
	}
	
    /**
     * �쒌궭�녈굮�쇌툔�쀣걼�쎼겗�ㅳ깧�녈깉�믥��녴걲�뗣궚�⒲궧
     * @param v
     */
    public class ButtonClickList implements OnClickListener{
    	public void onClick(View v){
			switch(v.getId()){
//			case R.id.create_button:
//				moveToCreateActivity();
//				break;
			default:
				break;
			}
    	}
    }

	class TrainListAdapter extends BaseAdapter{
		Context maincon;
		LayoutInflater Inflater;
		ArrayList<TrainEntry> arSrc;
		int layout;
		
		public TrainListAdapter(Context context, int alayout, ArrayList<TrainEntry> trainArray){
			maincon = context;
			Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			layout = alayout;
			arSrc = trainArray;
		}
	
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return arSrc.size();
		}
	
		@Override
		public TrainEntry getItem(int index) {
			// TODO Auto-generated method stub
			return arSrc.get(index);
		}
	
		@Override
		public long getItemId(int index) {
			// TODO Auto-generated method stub
			return index;
		}
	
		@Override
		public View getView(int index, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int position = index;
			final Button btn_on;
			final Button btn_off; //alarm button fix
			
			if(convertView == null)
				convertView = Inflater.inflate(layout,  parent, false);
			
			// 終電名称の表示
			TextView patternName = (TextView)convertView.findViewById(R.id.pattern_name);
			patternName.setText(arSrc.get(position).getName()); 
			
//			// 何分前の表示
//			TextView alarmOnoff = (TextView)convertView.findViewById(R.id.alarm_onoff);
//			String[] alarmString = getResources().getStringArray(R.array.spinner_time);
//			alarmOnoff.setText(alarmString[arSrc.get(position).getAlarmtime()]);
			
			// 終電まであと何分を表示
			TextView leftTime = (TextView)convertView.findViewById(R.id.alarm_onoff);
			TimeData trainTime = arSrc.get(position).getTrainTime();
			LeftTimeCalculate leftTimeCal = new LeftTimeCalculate();
			leftTime.setText(leftTimeCal.calAlarm(trainTime) + "後");
			
			
			// 終電名称押下時の処理
			patternName.setClickable(true);
			patternName.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					moveToDetailActivity(arSrc.get(position).getDbId());	
				}
			});
			// 終電名称長押しの場合の処理
			patternName.setOnLongClickListener(new View.OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					
					return false;
				}
			});

			// アラームボタンの表示・非表示
			btn_on = (Button)convertView.findViewById(R.id.alarm_btn_on);
			btn_off = (Button)convertView.findViewById(R.id.alarm_btn_off);
		    
		    // DBの情報に合わせて、ON/OFFを切り分け
			if(arSrc.get(position).getAlarmFlg() == 0){
				// OFF表示
				btn_on.setVisibility(View.INVISIBLE);
				btn_off.setVisibility(View.VISIBLE);
			}else{
				// ON表示
				btn_on.setVisibility(View.VISIBLE);
				btn_off.setVisibility(View.INVISIBLE);
			}

			// アラームONボタンの動作
		    btn_on.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// ONボタンを押下したらアラーム解除
					btn_on.setVisibility(View.INVISIBLE);
					btn_off.setVisibility(View.VISIBLE);
					// アラーム起動（解除）
					AlarmManageStart alarmAct = new AlarmManageStart(ListActivity.this);
					alarmAct.onCreateAlarm(false, 
							arSrc.get(position).getTrainTime().getHour(),
							arSrc.get(position).getTrainTime().getMinute(),
							arSrc.get(position).getAlarmtime(),
							arSrc.get(position).getDbId());
					
				}
			});
			// アラームOFFボタンの動作
		    btn_off.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// OFFボタンを押下したらアラーム設定
					btn_on.setVisibility(View.VISIBLE);
					btn_off.setVisibility(View.INVISIBLE);
					// アラーム起動（セット）
					AlarmManageStart alarmAct = new AlarmManageStart(ListActivity.this);
					alarmAct.onCreateAlarm(true, 
							arSrc.get(position).getTrainTime().getHour(),
							arSrc.get(position).getTrainTime().getMinute(),
							arSrc.get(position).getAlarmtime(),
							arSrc.get(position).getDbId());
				}
			});
		    
			return convertView;
		}
	}
	
	/** メニューキー押下でリンク画面へ移動 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.activity_route_view, menu);
//        return true;
    	
        MenuItem pref_item = menu.add("路線図へ");
        OnMenuItemClickListener listener = new OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                openPref();
                return false;
            }
        };
        pref_item.setOnMenuItemClickListener(listener);
        return true;
    }
     
    public void openPref(){
        Intent intent = new Intent(this, (Class<?>)RouteViewActivity.class);
        startActivity(intent);
    }

}
